package com.gjy.nwpufindseats.util;
import com.gjy.nwpufindseats.baseData.AllGrade;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.io.StreamCorruptedException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import com.gjy.nwpufindseats.R;
import com.gjy.nwpufindseats.baseData.Global;


@SuppressLint("SimpleDateFormat")
public class JwNetSpider {
	
	private static HttpClient hc = new DefaultHttpClient();
	private static HttpClient jwAppClient;
	private static HttpClient jwClient;
	public static String passwordString;
	public static SharedPreferences prefRoomInfo;
	public static Editor editorRoomInfo;
	public static Cookie cookie = null; 
	public static  Boolean axgdBoolean= true;
	
	/**
	 * 初次登录，并未保存密码，无需解密
	 * @param stuNum
	 * @param password
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public boolean firstLogin(Context mainContext, String stuNum,String password) throws ClientProtocolException, IOException//为false，则登录失败，为true，则成功
	{
		SharedPreferences loginInfoPreferences = mainContext.getSharedPreferences("user", Context.MODE_PRIVATE) ;

		if(loginInfoPreferences.getBoolean("method", false))
		{
			return firstTradLogin(stuNum,password);
		}
		else {
			return firstDigitalLogin(mainContext, stuNum,password);
		}
	}
	
	public boolean firstTradLogin(String stuNum,String password) throws ClientProtocolException, IOException{
		String loginUrl = "http://222.24.192.69/loginAction.do";
		//------------登录------
		List<NameValuePair> firstTradLogin = new ArrayList<NameValuePair>();
		firstTradLogin.add(new BasicNameValuePair("zjh", stuNum));
		firstTradLogin.add(new BasicNameValuePair("mm", password));
		String bodyString=post(loginUrl, firstTradLogin);
		Document doc = Jsoup.parse(bodyString);
		//密码错误网页会有class=errorTop元素
		Elements testElement =doc.getElementsByClass("errorTop");
		return testElement.isEmpty();	
	}
	
	/**
	 * 利用数字工大进入教务的方式
	 * @param mainContext
	 * @param stuNum
	 * @param password
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public boolean firstDigitalLogin(Context mainContext, String stuNum,String password) throws ClientProtocolException, IOException{
		String encodedService="http%3a%2f%2fportal.nwpu.edu.cn%2fdcp%2findex.jsp";
		String service ="http://portal.nwpu.edu.cn/dcp/index.jsp" ;
		String server = "http://cas.nwpu.edu.cn/cas/login";

        HttpPost httpPost = new HttpPost(server);
        HttpResponse httpRespone = new DefaultHttpClient().execute(httpPost);
        HttpEntity httpEntity = httpRespone.getEntity();
        InputStream inputStream = httpEntity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                        inputStream));
        String str = "";
        String line = null;
        while ((line = reader.readLine()) != null) {
                str += line;
        }
        if(Jsoup.parse(str).select("input[name=lt]").isEmpty())
        {
        	axgdBoolean =false;
        	return false;
        }
        //获取页面lt
        String center = Jsoup.parse(str).select("input[name=lt]").get(0).attr("value").toString();
        
        
      //------------登录的中间跳转页面------
      		List<NameValuePair> firstDigitalLogin = new ArrayList<NameValuePair>();
      		firstDigitalLogin.add(new BasicNameValuePair("username", stuNum));
      		firstDigitalLogin.add(new BasicNameValuePair("password", password));
      		firstDigitalLogin.add(new BasicNameValuePair("service", service));
      		firstDigitalLogin.add(new BasicNameValuePair("lt", center));
      		firstDigitalLogin.add(new BasicNameValuePair("encodedService", encodedService));
      		
      		String casJsp=post(server, firstDigitalLogin);
      		String sucess = Jsoup.parse(casJsp).select("title").get(0).text();
      		if(!"CAS认证转向".equals(sucess))
      		{
      			return false;
      		}
      		String realJspString = Jsoup.parse(casJsp).select("a[href]").get(0).attr("href").toString();
      	
      		
      		//-----------------登录界面------------
      		HttpGet httpGet = new HttpGet(realJspString);
      		jwClient = new DefaultHttpClient();
      		jwClient.execute(httpGet);
			
			
			
			String serviceJwApp ="http://222.24.192.69/mhLogin.jsp";	
			
			
			List<NameValuePair> jwLogin = new ArrayList<NameValuePair>();
      		jwLogin.add(new BasicNameValuePair("service", serviceJwApp));
      		String jwJsp=get(server, jwLogin);
      		String JwAppString  = Jsoup.parse(jwJsp).select("a[href]").get(0).attr("href").toString();
      		HttpGet jwAppClientGet = new HttpGet(JwAppString);
      		jwAppClient = new DefaultHttpClient();
      		//-----打印Location头-------
      		HttpParams params = jwAppClient.getParams();  
      		params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);  
      		HttpResponse jwAppEntityResponse = jwAppClient.execute(jwAppClientGet);
			Header[] headers = jwAppEntityResponse.getAllHeaders();

			    String allString = headers[2].getValue();
			    String a[] = allString.split("=");
			    String tradJwUrl="http://222.24.192.69/loginAction.do";
			    String dlfs= "mh";
			    String mh_zjh = stuNum;
			   String mh_mm= a[3];
			   			  			    
			//传统教务进入
			   List<NameValuePair> tradJwLogin = new ArrayList<NameValuePair>();
			   tradJwLogin.add(new BasicNameValuePair("dlfs", dlfs));
			   tradJwLogin.add(new BasicNameValuePair("mh_zjh", mh_zjh));
			   tradJwLogin.add(new BasicNameValuePair("mh_mm", mh_mm));
				post(tradJwUrl, tradJwLogin);
				
				//为了方便下次使用，将跳过数字工大登录方式，直接用获得的已加密数据登录教务网。
				SharedPreferences loginInfoPreferences = mainContext.getSharedPreferences("user", Context.MODE_PRIVATE) ;
				Editor loginInfoEditor = loginInfoPreferences.edit();
				try {
					passwordString = AESEncryptor.encrypt(Global.rawKey, mh_mm);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				loginInfoEditor.putString("password", passwordString);
				loginInfoEditor.commit();
				return true;
			
			

	}
	/**
	 * 以后登录检测，需要反解密码
	 * @param stuNum
	 * @param password
	 * @return true为正常登录，false为密码错误
	 */
	public static boolean login(Context mainContext, String stuNum,String password)//为false，则登录失败，为true，则成功
	{
		
		
		String passwordString = null;
		try {
 			passwordString = AESEncryptor.decrypt(Global.rawKey, password);
 			
 		} catch (Exception e1) {
 			// TODO Auto-generated catch block
 			e1.printStackTrace();
 		}
		SharedPreferences loginInfoPreferences = mainContext.getSharedPreferences("user", Context.MODE_PRIVATE) ;
		
		if(loginInfoPreferences.getBoolean("method", false))
		{
			return tradLogin(stuNum,passwordString);			
		}
		else {
			return digitalLogin(stuNum,passwordString);
		}

	}
	
	public static boolean tradLogin(String stuNum,String password)
	{
		String loginUrl = "http://222.24.192.69/loginAction.do";
		List<NameValuePair> tradLogin = new ArrayList<NameValuePair>();
		tradLogin.add(new BasicNameValuePair("zjh", stuNum));
		tradLogin.add(new BasicNameValuePair("mm", password));
		String bodyString=post(loginUrl, tradLogin);
		Document doc = Jsoup.parse(bodyString);
		//密码错误网页会有class=errorTop元素
		Elements testElement =doc.getElementsByClass("errorTop");
		return testElement.isEmpty();	
	}
	
	public static boolean digitalLogin(String stuNum,String password)
	{
		String tradJwUrl="http://222.24.192.69/loginAction.do";
	    String dlfs= "mh";
		List<NameValuePair> tradJwLogin = new ArrayList<NameValuePair>();
		   tradJwLogin.add(new BasicNameValuePair("dlfs", dlfs));
		   tradJwLogin.add(new BasicNameValuePair("mh_zjh", stuNum));
		   tradJwLogin.add(new BasicNameValuePair("mh_mm", password));
		   String bodyString =post(tradJwUrl, tradJwLogin);
			Document doc = Jsoup.parse(bodyString);
			//密码错误网页会有class=errorTop元素
			Elements testElement =doc.getElementsByClass("errorTop");
			return testElement.isEmpty();	
			
	}
	/**
	 * 解密方式登录翱翔门户
	 * @param stuNum
	 * @param password
	 * @return
	 * @throws IOException
	 */
	public static boolean digitalHomeLogin(String stuNum,String password) throws IOException
	{
		String passwordString = null;
		try {
			passwordString = AESEncryptor.decrypt(Global.rawKey, password);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String encodedService="http%3a%2f%2fportal.nwpu.edu.cn%2fdcp%2findex.jsp";
		String service ="http://portal.nwpu.edu.cn/dcp/index.jsp" ;
		String server = "http://cas.nwpu.edu.cn/cas/login";

        HttpPost httpPost = new HttpPost(server);
        HttpResponse httpRespone = new DefaultHttpClient().execute(httpPost);
        HttpEntity httpEntity = httpRespone.getEntity();
        InputStream inputStream = httpEntity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                        inputStream));
        String str = "";
        String line = null;
        while ((line = reader.readLine()) != null) {
                str += line;
        }
        if(Jsoup.parse(str).select("input[name=lt]").isEmpty())
        {
        	axgdBoolean =false;
        	return false;
        }
        //获取页面lt
        String center = Jsoup.parse(str).select("input[name=lt]").get(0).attr("value").toString();
        
        
      //------------登录的中间跳转页面------
      		List<NameValuePair> firstDigitalLogin = new ArrayList<NameValuePair>();
      		firstDigitalLogin.add(new BasicNameValuePair("username", stuNum));
      		firstDigitalLogin.add(new BasicNameValuePair("password", passwordString));
      		firstDigitalLogin.add(new BasicNameValuePair("service", service));
      		firstDigitalLogin.add(new BasicNameValuePair("lt", center));
      		firstDigitalLogin.add(new BasicNameValuePair("encodedService", encodedService));
      		
      		String casJsp=post(server, firstDigitalLogin);
      		String sucess = Jsoup.parse(casJsp).select("title").get(0).text();
      		if(!"CAS认证转向".equals(sucess))
      		{
      			return false;
      		}
      		String realJspString = Jsoup.parse(casJsp).select("a[href]").get(0).attr("href").toString();
      	
      		
      		//-----------------登录界面------------
      		HttpGet httpGet = new HttpGet(realJspString);
      		jwClient = new DefaultHttpClient();
      		HttpResponse httpresponse  = jwClient.execute(httpGet);
      		
      		HttpEntity entity = httpresponse.getEntity();
			EntityUtils.toString(entity);
      		List<Cookie> cookies = ((AbstractHttpClient) jwClient).getCookieStore().getCookies();  
      		if (!cookies.isEmpty()) {  
      		    for (int i = 0; i < cookies.size(); i++) {  
      		        cookie = cookies.get(i);  
      		    }  
      		}  
      		return true;	
	}
	
	public static Cookie  lost(String stuNum,String password)
	{

		try {
			digitalHomeLogin(stuNum, password);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return cookie;
	}
	
	
	
	
	/**
	 * 成绩查询
	 * @param stuNum
	 * @param password
	 * @return
	 */
	public static ArrayList<String> getGrade(Context mainContext,String stuNum,String password)
	{
		String gradeUrl = "http://222.24.192.69/bxqcjcxAction.do";
		ArrayList<String>gradeArrayList = new ArrayList<String>();
		if(!login(mainContext,stuNum, password))
		{			
			gradeArrayList.add("0");//密码错误，返回0值
			
		}
		else //登录成功，进行成绩查询
			{
			List<NameValuePair> paramsGrade = new ArrayList<NameValuePair>();
			paramsGrade.add(new BasicNameValuePair("pageSize","300"));
			String body = get(gradeUrl, paramsGrade);
			
			Document doc = Jsoup.parse(body);
			ArrayList<String> grades = new ArrayList<String>();//用于存放所有信息
			Elements center = doc.select("tr>td[align=center]");	
			if(!doc.getElementsByClass("errorTop").isEmpty())
			{
				gradeArrayList.add("1");//网页打开有误，返回1值。
				
			}
			else if(center.isEmpty())
			{
				gradeArrayList.add("3");//网页没有有效数据，返回3值。
				
			}
			else//网页成功获取数据
			{
				for(Element e: center)
				{
					grades.add(e.text());
				}
				gradeArrayList=selectGrades(grades);
			}
			}
		return gradeArrayList;
	}
	/**
	 * 所有成绩查询
	 * @param mainContext
	 * @param stuNum
	 * @param password
	 * @return
	 */
	public static ArrayList<String> getAllGrade(Context mainContext,String stuNum,String password)
	{
		String allGradeUrl = "http://222.24.192.69/gradeLnAllAction.do";
		ArrayList<String>gradeArrayList = new ArrayList<String>();
		if(!login(mainContext,stuNum, password))
		{			
			gradeArrayList.add("0");//密码错误，返回0值
			
		}
		else //登录成功，进行成绩查询
			{
			List<NameValuePair> paramsGrade = new ArrayList<NameValuePair>();
			paramsGrade.add(new BasicNameValuePair("oper","sxinfo"));
			String body = get(allGradeUrl, paramsGrade);
			
			Document doc = Jsoup.parse(body);
			
			ArrayList<String> grades = new ArrayList<String>();//用于存放所有信息
			Elements center = doc.select("tr>td[align=center]");	
			if(!doc.getElementsByClass("errorTop").isEmpty())
			{
				gradeArrayList.add("1");//网页打开有误，返回0值。
				
			}
			else//网页成功获取数据
			{
				for(Element e: center)
				{
					grades.add(e.text());
				}
				gradeArrayList=selectAllGrades(grades);
			}
			}
		return gradeArrayList;
	}
	
	public static ArrayList<String> getbjgGrade(Context mainContext,String stuNum,String password)
	{
		String bjgGradeUrl = "http://222.24.192.69/gradeLnAllAction.do";
		ArrayList<String>gradeArrayList = new ArrayList<String>();
		if(!login(mainContext,stuNum, password))
		{			
			gradeArrayList.add("0");//密码错误，返回0值
			
		}
		else //登录成功，进行成绩查询
			{
			List<NameValuePair> paramsGrade = new ArrayList<NameValuePair>();
			paramsGrade.add(new BasicNameValuePair("type","ln"));
			paramsGrade.add(new BasicNameValuePair("oper","bjg"));
			
			String body = get(bjgGradeUrl, paramsGrade);
			ArrayList<String> selectGrade = new ArrayList<String>();
			Document doc = Jsoup.parse(body);	
			if(!doc.getElementsByClass("errorTop").isEmpty())
			{
				gradeArrayList.add("1");//网页打开有误，返回1值。
				return gradeArrayList;
			}
			ArrayList<String> grades = new ArrayList<String>();
			Element sbjg = doc.select("table[class=titleTop2]").get(0);//得到第一组数据  尚不及格
			Elements sbjgElements = sbjg.select("tr[class=odd]").select("tr>td[align=center]");
			Element cbjg = doc.select("table[class=titleTop2]").get(1);//得到第二组数据  曾不及格
			Elements cbjgElements = cbjg.select("tr[class=odd]").select("tr>td[align=center]");
			
			selectGrade.add("尚不及格");
			selectGrade.add(" ");
			for(Element e: sbjgElements)
			{
				grades.add(e.text());
			}
			for(int index=2;index<grades.size();)
			{
				selectGrade.add(grades.get(index));
				if(index%9==6)
				index=index+1;
				index=index+4;
			}
			selectGrade.add("曾不及格");
			selectGrade.add(" ");
			for(Element e: cbjgElements)
			{
				grades.add(e.text());
			}
			for(int index=2;index<grades.size();)
			{
				selectGrade.add(grades.get(index));
				if(index%9==6)
				index=index+1;
				index=index+4;
			}
			gradeArrayList = selectGrade;
		}
		return gradeArrayList;
	}
	
	public static ArrayList<AllGrade> getAllJgGrade(Context mainContext,String stuNum,String password)
	{
		String JgGradeUrl = "http://222.24.192.69/gradeLnAllAction.do";
		ArrayList<String>gradeArrayList = new ArrayList<String>();
		ArrayList<AllGrade> allGrades= new ArrayList<AllGrade>();
		if(!login(mainContext,stuNum, password))
		{			
			gradeArrayList.add("0");//密码错误，返回0值
			
		}
		else //登录成功，进行成绩查询
			{
			List<NameValuePair> paramsGrade = new ArrayList<NameValuePair>();
			paramsGrade.add(new BasicNameValuePair("type","ln"));
			paramsGrade.add(new BasicNameValuePair("oper","qbinfo"));
			String body = get(JgGradeUrl, paramsGrade);
			
			Document doc = Jsoup.parse(body);
			if(!doc.getElementsByClass("errorTop").isEmpty())//网页错误
			{
				allGrades.clear();
				return allGrades;
			}
			Elements aElements = doc.select("a");//获取学期标题
			int length  = aElements.size();
			
			
			ArrayList<String> termName = new ArrayList<String>();
			for(Element e: aElements)
			{
				termName.add(e.attr("name"));
			}
			ArrayList<Elements> allElements = new ArrayList<Elements>();
			ArrayList<ArrayList<String>> selectGrade = new ArrayList<ArrayList<String>>();
			for(int i=0;i<length;i++){
				
				
				allElements.add((doc.select("table[class=titleTop2]").get(i)).select("tr[class=odd]").select("tr>td[align=center]"));
				ArrayList<String> grades = new ArrayList<String>();
				for(Element e: allElements.get(i))
				{
					grades.add(e.text());
				}
				ArrayList<String> selectSecGrade = new ArrayList<String>();
				for(int index=2;index<grades.size();)
				{
					selectSecGrade.add(grades.get(index));
					if(index%7==2)
					index=index+1;
					index=index+3;
				}
				selectGrade.add(selectSecGrade);
				allGrades.add(new AllGrade(termName.get(i),selectGrade.get(i)));
			}
			}
		return allGrades;
	}
	
	
	/**
	 * 得到教室信息的动态字符串数组
	 * @param args
	 * @throws SQLException 
	 * @throws IOException 
	 * @throws ClassNotFoundException 
	 */
	public static ArrayList<String> getOccupiedRoom(Context mainContext,String stuNum,String password,String apartmentNum) throws  IOException, ClassNotFoundException
	{
		ArrayList<String>occpiedRoom = new ArrayList<String>();
		if(isThisWeekData(mainContext, apartmentNum))//为本周数据，无需登录教务联网下载
		{
			occpiedRoom=getLocalData(mainContext,apartmentNum);
		}
		else
		{//保存数据非本周数据，需登录教务重新加载数据
			occpiedRoom = getNetData(mainContext,stuNum,password,apartmentNum);
		}
		return occpiedRoom;
				
	}
	
	@SuppressWarnings("unchecked")
	public static ArrayList<String> getLocalData(Context mainContext,String apartmentNum) throws StreamCorruptedException, IOException, ClassNotFoundException
	{
		ArrayList<String> oneDayData = new ArrayList<String>();
		SimpleDateFormat dfWeek = new SimpleDateFormat("E");//设置日期格式
		String weekDay=dfWeek.format(new Date()).toString();
		int startDate = getWeekDay(mainContext,weekDay);
		String filenameString = apartmentNum+startDate+".txt";	 
		FileInputStream fis = mainContext.openFileInput(filenameString);
		ObjectInputStream ois = new ObjectInputStream(fis);
		oneDayData = (ArrayList<String>)ois.readObject();
	    ois.close();//关闭文件输入输出流*/
	    return oneDayData;	
	}
	
	
	//联网获取数据
	public static ArrayList<String> getNetData(Context mainContext,String stuNum,String password,String apartmentNum)
	{
		ArrayList<String> occpiedRoomAll = new ArrayList<String>();
		ArrayList<String> oneDayData = new ArrayList<String>();
		Document doc = null;
		String selectUrl = "http://222.24.192.69/wkjasAction.do";
		String xqh;
		//选择校区
		if("02".equals(apartmentNum))
		{
			 xqh = "01";//老校区
		}
		else
		{
			 xqh = "02";//新校区
		}
		//登录是否成功
		if(!login(mainContext,stuNum, password))
		{			
			occpiedRoomAll.add("0");//密码错误，返回0值
			return occpiedRoomAll;
		}
		else {//登录成功						
				//----------教室使用页面跳转-------
				List<NameValuePair> paramsApart = new ArrayList<NameValuePair>();
				paramsApart.add(new BasicNameValuePair("oper", "ori"));
				paramsApart.add(new BasicNameValuePair("xqh", xqh));
				paramsApart.add(new BasicNameValuePair("jxlh", apartmentNum));
				post(selectUrl, paramsApart);
		
				//Get页面
				List<NameValuePair> params2Get = new ArrayList<NameValuePair>();
				params2Get.add(new BasicNameValuePair("oper", "jasxx"));
				
				//网页正式数据：：：：
				String body = get(selectUrl, params2Get);
				
				doc = Jsoup.parse(body);
	        }	
		Elements bgcolors = doc.select("td[bgcolor]"); 
		if(bgcolors.isEmpty())
		{
			occpiedRoomAll.add("1");//网页有误，打开错误，返回"1"
			return occpiedRoomAll;
		}
		else//成功获取教室信息表格图，进行星期转换，抓取数据
		{
			for(Element e:bgcolors)
			{
				occpiedRoomAll.add(e.attr("bgcolor").toString());
			}
			SimpleDateFormat dfWeek = new SimpleDateFormat("E");//设置日期格式
			String weekDay=dfWeek.format(new Date()).toString();
			int startDate = getWeekDay(mainContext,weekDay);	
			oneDayData= getData(mainContext,occpiedRoomAll,apartmentNum,startDate);//获取数据，写入相应文件
		}	
		return oneDayData;
	}
	
	
	public static ArrayList<String> offDownRoom(Context mainContext,String stuNum,String password,String apartmentNum) 
	{
		String selectUrl = "http://222.24.192.69/wkjasAction.do";
		String xqh;
		//选择校区
		if("02".equals(apartmentNum))
		{
			 xqh = "01";
		}
		else
		{
			 xqh = "02";
		}
		ArrayList<String>occpiedRoomAll = new ArrayList<String>();
		if(!login(mainContext,stuNum, password))
		{			
			occpiedRoomAll.add("0");//密码错误，返回0值
		}
		else {//登录成功		
			//----------教室使用页面跳转-------
			List<NameValuePair> paramsApart = new ArrayList<NameValuePair>();
			paramsApart.add(new BasicNameValuePair("oper", "ori"));
			paramsApart.add(new BasicNameValuePair("xqh", xqh));
			paramsApart.add(new BasicNameValuePair("jxlh", apartmentNum));
			post(selectUrl, paramsApart);
	
			//Get页面
			List<NameValuePair> params2Get = new ArrayList<NameValuePair>();
			params2Get.add(new BasicNameValuePair("oper", "jasxx"));
			
			//正式数据：：：：
			String body= get(selectUrl, params2Get);
			Document doc = Jsoup.parse(body);
				
			//Jsoup获取页面颜色分布	
			Elements bgcolors = doc.select("td[bgcolor]"); 
			
			if(bgcolors.isEmpty())
			{
				occpiedRoomAll.add("1");//网页有误，打开错误，返回"1"
			}
			else//成功获取教室信息表格图，进行星期转换，抓取数据
			{
				for(Element e:bgcolors)
				{
					occpiedRoomAll.add(e.attr("bgcolor").toString());
				}
				for(int i=0;i<7;i++)
				writeData(mainContext,occpiedRoomAll,apartmentNum,i);//登录成功，一切数据正常，则将生成的Doc写入文件
			}			
		}
		return occpiedRoomAll;
	}
	
	



	/**
	 * Get请求
	 * @param url
	 * @param params
	 * @return
	 */
	public static String get(String url, List<NameValuePair> params) {
		String body = null;
		try {
			// Get请求
			HttpGet httpget = new HttpGet(url);
			// 设置参数
			String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
			httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));
			// 发送请求
			HttpResponse httpresponse = hc.execute(httpget);
			// 获取返回数据
			HttpEntity entity = httpresponse.getEntity();
			body = EntityUtils.toString(entity);
			if (entity != null) {
				entity.consumeContent();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		return body;
	}

	/**
	 * // Post请求
	 * @param url
	 * @param params
	 * @return
	 */
	public static String post(String url, List<NameValuePair> params) {
		String body = null;
		try {
			// Post请求
			HttpPost httppost = new HttpPost(url);
			// 设置参数
			httppost.setEntity(new UrlEncodedFormEntity(params));
			// 发送请求
			HttpResponse httpresponse = hc.execute(httppost);
			// 获取返回数据
			HttpEntity entity = httpresponse.getEntity();
			body = EntityUtils.toString(entity);
			if (entity != null) {
				entity.consumeContent();
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return body;
	}
	


	/**
	 *分析教室数据，提取有效信息
	 * @param bgcolors
	 * @throws SQLException 
	 */
	public static ArrayList<String> getData(Context mainContext,ArrayList<String> occupiedRoomAll,String apartmentNum,int startDate) 
	{
		
		String [] apartment;
		int index;
		if("31".equals(apartmentNum))
		{
			apartment=Global.roomXa;
			index=70;//A100不计
		}
		else if("33".equals(apartmentNum))
		{
			apartment=Global.roomXc;
			index=280;//四间教室不存在
		}
		else if("34".equals(apartmentNum))
		{
			apartment=Global.roomXd;
			index=70;//D100不计
		}
		else
		{
			apartment=Global.roomXg;
			index =0;
		}
		index = index +startDate*10;
		ArrayList<String> occupiedRoom = new ArrayList<String>();
		for(;index<occupiedRoomAll.size();)
		{
			
			for(int iroom=0;iroom<apartment.length;iroom++)
			{								
					occupiedRoom.add(apartment[iroom]);
					//String[] lsx =new String []{apartment[iroom],"1","1","1","1","1"};
						for(int iclass=0;iclass<5;iclass++)//每天5节课
						{
							if("white".equals(occupiedRoomAll.get(index)))
							{
								occupiedRoom.add("0");
							}
							else 
								occupiedRoom.add("1");
							index++;
							index++;//最内层循环，index+2
						}//for iclass
						index = index+60;//换下一间教室
			}//for iroom
		}//for index
		return occupiedRoom;			
	}
	
	public static void writeData(Context mainContext,ArrayList<String> occupiedRoomAll,String apartmentNum,int weekDay)
	{
		String filename = apartmentNum+weekDay+".txt";//保存文件名
		ArrayList<String> oneDayData;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		prefRoomInfo = mainContext.getSharedPreferences("downloaddate", Context.MODE_PRIVATE);
		editorRoomInfo = prefRoomInfo.edit();
		editorRoomInfo.putString(apartmentNum,df.format(new Date()).toString());	
		editorRoomInfo.commit();
		oneDayData=getData(mainContext,occupiedRoomAll,apartmentNum,weekDay);
		try
		{
			//BufferedOutputStream bufferedOutputStream =   
	          //      new BufferedOutputStream(new FileOutputStream(filename));
			//bufferedOutputStream.write(buffer)
			// 以private模式打开文件输出流
			FileOutputStream fos = mainContext.openFileOutput(filename, Context.MODE_PRIVATE);
			// 将FileOutputStream包装成ObjectOutputStream
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(oneDayData);
			oos.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 从传来的成绩列表获取最有用信息，即课程中文名和成绩，并返回
	 * @param grades
	 * @return
	 */
	public static ArrayList<String> selectGrades(ArrayList<String> grades)
	{
		ArrayList<String> selectGrade = new ArrayList<String>();
		for(int index=2;index<grades.size();)
		{
			selectGrade.add(grades.get(index));
			index=index+4;
		}
		return selectGrade;
	}
	
	/**
	 * 从传来的成绩列表获取最有用信息，即课程中文名和成绩，并返回
	 * @param grades
	 * @return
	 */
	public static ArrayList<String> selectAllGrades(ArrayList<String> grades)
	{
		ArrayList<String> selectGrade = new ArrayList<String>();
		for(int index=2;index<grades.size();)
		{
			selectGrade.add(grades.get(index));
			if(index%7==2)
			{
				index=index+4;
			}				
			else {
				index = index+3;
			}
		}
		return selectGrade;
	}
	
	
	public static int getWeekDay(Context mainContext,String weekDay)
	{	
		Resources res =mainContext.getResources();
		int startDate;
		if(res.getString(R.string.weekday1).equals(weekDay))
		{
			startDate=0;
		}
		else if(res.getString(R.string.weekday2).equals(weekDay))
		{
			startDate=1;
		}
		else if(res.getString(R.string.weekday3).equals(weekDay))
		{
			startDate=2;
		}
		else if(res.getString(R.string.weekday4).equals(weekDay))
		{
			startDate=3;
		}
		else if(res.getString(R.string.weekday5).equals(weekDay))
		{
			startDate=4;
		}
		else if(res.getString(R.string.weekday6).equals(weekDay))
		{
			startDate=5;
		}
		else 
		{
			startDate=6;
		}
		return startDate;
	}
	
	public static Boolean isThisWeekData(Context mainContext,String apartmentNum)
	{
		Boolean is = true; 
		prefRoomInfo = mainContext.getSharedPreferences("downloaddate", Context.MODE_PRIVATE);
		editorRoomInfo = prefRoomInfo.edit();
		String savedDateString = prefRoomInfo.getString(apartmentNum, "0");
		if("0".equals(savedDateString))//返回0，则没有本地数据
		{
			is = false;
			return is;
		}
		SimpleDateFormat savedDate = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		SimpleDateFormat savedDateWeekDay = new SimpleDateFormat("E");//周几		
		String weekDay = null;
		try {
			weekDay = savedDateWeekDay.format(savedDate.parse(savedDateString)).toString();
		} catch (java.text.ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//得到周几
		int day = getWeekDay(mainContext,weekDay);//得到该周的第几天减一
		long savedDateLong = 0;
		try {
			savedDateLong = savedDate.parse(savedDateString).getTime();
		} catch (java.text.ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        long tmpDate = new Date().getTime();//得到当前时间
        long dDays = (tmpDate-savedDateLong)/(1000*60*60*24)+day;//当日和保存日期该周的周一的差
		if("0".equals(savedDateString)||dDays>=7)//之前没有下载数据或者下载数据不是本周数据
		{
			is = false;
		}
		else 
		{
			is = true;
		}
		
		return is;
	}
	public static HttpClient getHc() {
		return hc;
	}

	public static void setHc(HttpClient hc) {
		JwNetSpider.hc = hc;
	}
	
	public static void resetHc()
	{
		hc=new DefaultHttpClient();		
	}
}


